package com.zzw.springcloud.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Slf4j
@Component
public class CustomGatewayFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //http://localhost:20000/member/provider/selectById/1?user=zzw&pwd=123456
        //使用ServerWebExchange获取请求参数，通过getQueryParameters()和getFirst()方法提取特定参数
        String user = exchange.getRequest().getQueryParams().getFirst("user");
        String pwd = exchange.getRequest().getQueryParams().getFirst("pwd");
        log.info("user: {}, pwd: {}", user, pwd);

        if (!"zzw".equals(user) || !"123456".equals(pwd)) {
            //不满足条件返回406状态码，该状态码表示客户端发送的请求不被服务器接受，用于告知客户端请求存在问题。
            //设置状态码：HttpStatus.NOT_ACCEPTABLE
            //结束响应：exchange.getResponse().setComplete()
            exchange.getResponse().setStatusCode(HttpStatus.NOT_ACCEPTABLE);
            return exchange.getResponse().setComplete();
        }

        //放行条件：当参数验证通过时
        //实现方式：调用chain.filter(exchange)将请求传递到下一个过滤器或服务
        //链式处理：Gateway支持多个过滤器形成执行链，通过Ordered接口控制执行顺序
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
